package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Override
    public Result findAll(String username) {
        try {
            //根据用户名查询数据库
            com.itheima.pojo.User user1 = menuDao.findByusername(username);
            //根据用户id查询角色并封装菜单信息
            Set<Role> roleSet = menuDao.findAll(user1.getId());
            //创建一个set集合用来存储没有自关联的菜单
            List<Menu> menus = new ArrayList<>();
            for (Role role : roleSet) {
                //根据角色id查询菜单
                List<Menu> menuSet = menuDao.findByMenu(role.getId());
                for (Menu menu : menuSet) {
                    List<Menu> list = new ArrayList<>();
                    if (menu.getParentMenuId()==null){
                        menu.setTitle(menu.getName());
                        //如果是主菜单 再次进行遍历查询子菜单
                        for (Menu menu1 : menuSet) {
                            if (menu.getId()==menu1.getParentMenuId()){
                                menu1.setTitle(menu1.getName());
                                //说明是子菜单
                                list.add(menu1);
                            }
                        }
                        menu.setChildren(list);
                        menus.add(menu);
                    }
                }
            }
            return new Result(true,"查询菜单成功",menus);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询菜单失败");
        }
    }

}
